package com.lx.shopping.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lx.bean.Result;
import com.lx.bilibili.entity.Order;
import com.lx.bilibili.entity.OrderEx;
import com.lx.bilibili.entity.Product;
import com.lx.shopping.dao.OrderMapper;
import com.lx.shopping.dao.ProductExMapper;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lx
 * @since 2025-04-13
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ProductExMapper productExMapper;

    @RequestMapping("saveOrder")
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Result saveOrder(@RequestBody Order order){

        try {
            LambdaUpdateWrapper<Product> luw = new LambdaUpdateWrapper<>();
            luw.eq(Product::getId,order.getPid()).setSql("nums = nums - " + order.getNums());
            productExMapper.update(luw);
            order.setOrdertime( new Timestamp(System.currentTimeMillis()));
            System.out.println("order = " + order);
            if (orderMapper.insert(order) > 0) {
                return new Result(1, "购买成功", null);
            }else{
                return new Result(0, "购买失败，请稍后再试", null);
            }
        } catch (Exception e) {
            // 发生异常时重置自增序列
            Integer nextVal = orderMapper.getNextAutoIncrementValue();
            orderMapper.setAutoIncrement(nextVal != null ? nextVal : 1);
            throw e;
        }
    }

    @RequestMapping("getOrderById")
    public Result getOrderById(int id, int page, int size){
        page = (page - 1) * size;
        List<OrderEx> orders = orderMapper.getOrderByUserId(id, page, size);
        if(orders == null){
            return new Result(0, "暂无数据", null);
        }else {
            return new Result(1, "查询成功", orders);
        }
    }

    @RequestMapping("getOrderCountById")
    public Long getOrderCountById(int id){
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getUid,id);
        return orderMapper.selectCount(lqw);
    }

    @RequestMapping("canelOrder")
    public Result canelOrder(int id){
        LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper<>();
        luw.eq(Order::getId,id).set(Order::getState,2);
        orderMapper.update(luw);
        return new Result(1, "取消成功", null);
    }

}
